package com.dingreading.cloud.admin.controller;

import com.dingreading.cloud.admin.entity.StoreProjects;
import com.dingreading.cloud.admin.entity.Subjects;
import com.dingreading.cloud.admin.feign.SomsFeignService;
import com.dingreading.cloud.admin.service.*;
import com.dingreading.cloud.admin.util.ProjectCycleUtil;
import com.dingreading.cloud.admin.util.redis.RedisService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.PageBeanDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.dingreading.cloud.common.util.RedisParam;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(value = "/system/storeProjects/v2")
@Api(tags = "总部-门店服务管理")
public class StoreProjectsControllerV2 {

    @Resource
    protected StoreProjectsService storeProjectsService;
    @Resource
    protected StoreProductLogsService productLogsService;
    @Resource
    protected CaScheduleLessonService scheduleLessonService;
    @Resource
    protected StoresService storesService;
    @Resource
    protected CmservicesService cmservicesService;
    @Resource
    protected RedisService redisService;
    @Resource
    protected SomsFeignService somsFeignService;
    @Resource
    private SubjectsService subjectsService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务名称") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "活动状态 1.可排活动 0.不可排活动") @RequestParam(value = "lessonStatus", required = false) Integer lessonStatus,
            @ApiParam(value = "活动次数状态 1.消耗次数 0.不消耗次数") @RequestParam(value = "freeStatus", required = false) Integer freeStatus,
            @ApiParam(value = "数据来源 1.总部 2.门店") @RequestParam(value = "source") Integer source,
            @ApiParam(value = "启用状态") @RequestParam(value = "enabled", required = false) Integer enabled,
            @ApiParam(value = "门店合作类型") @RequestParam(value = "cooperationType", required = false) String cooperationType
    ) {
        Page<StoreProjects> pageList = storeProjectsService.pageList(
                pageUtil, keyword, lessonStatus, freeStatus, source, enabled, cooperationType
        );

        PageBeanDto data = new PageBeanDto();
        data.setTotal(pageList.getTotalRow());
        data.setList(pageList.getRecords());
        return R.ok(data);
    }


    @ApiOperation(value = "获取信息")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid") String uid
    ) {
        StoreProjects data = storeProjectsService.getByUid(uid);
        return R.ok(data);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "创建/编辑信息")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid", required = false) String uid,
            @ApiParam(value = "服务名称") @RequestParam(value = "projectName") String projectName,
            @ApiParam(value = "活动状态 1.可排活动 0.不可排活动") @RequestParam(value = "lessonStatus") Integer lessonStatus,
            @ApiParam(value = "活动次数状态 1.消耗次数 0.不消耗次数") @RequestParam(value = "freeStatus", required = false) Integer freeStatus,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(value = "门店合作类型") @RequestParam(value = "cooperationType") String cooperationType,
            @ApiParam(value = "运营类型") @RequestParam(value = "operationType") String operationType,
            @ApiParam(value = "是否收取激活金额（0.不收费，1.收费）") @RequestParam(value = "isPay") Integer isPay,
            @ApiParam(value = "科目uid") @RequestParam(value = "subjectUid", required = false) String subjectUid
    ) {
        boolean b = storeProjectsService.haveName(uid, projectName);
        if (b)
            return R.fail("服务名称重复了");
        if (isPay == null)
            return R.fail("请选择是否收取激活金额");

        String subjectUidName = null;
        if (StringUtils.isNotBlank(subjectUid)) {
            Subjects subjects = subjectsService.getByUid(subjectUid);
            if (subjects == null)
                return R.fail("科目信息为空!");
            subjectUidName = subjects.getSubjectName();
        }

        if (StringUtils.isBlank(uid)) {
            // 创建
            // 获取最大的主渠道展示序号
            int maxOrderNum = storeProjectsService.getMaxOrderNum() + 1;

            StoreProjects data = ProjectCycleUtil.newProject(
                    null, null, projectName, lessonStatus, freeStatus, maxOrderNum, 1,
                    remark, headStaffUid, headStaffName, cooperationType, operationType, isPay, subjectUid, subjectUidName
            );
            storeProjectsService.saveOrUpdate(data);
        } else {
            // 编辑
            StoreProjects data = storeProjectsService.getByUid(uid);
            if (null == data)
                return R.fail("服务获取失败");
            if (!data.getSource().equals(1))
                return R.fail("非总部信息不能操作");

            // 判断服务是否被使用
            if (!data.getProjectName().equals(projectName)) {
                String msg = useProject(uid);
                if (StringUtils.isNotBlank(msg))
                    return R.fail(msg);
            }

            b = storeProjectsService.updateInfoV2(
                    uid, projectName, cooperationType, operationType, headStaffUid, headStaffName, isPay, subjectUid, subjectUidName
            );
            if (!b)
                return R.fail("更新失败");
        }

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE);

        return R.ok();
    }


    @ApiOperation(value = "删除信息")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid") String uid
    ) {
        StoreProjects data = storeProjectsService.getByUid(uid);
        if (null == data)
            return R.fail("获取失败");
        if (!data.getSource().equals(1))
            return R.fail("非总部信息不能操作");

        // 判断服务是否被使用
        String msg = useProject(uid);
        if (StringUtils.isNotBlank(msg))
            return R.fail(msg);

        long i = storeProjectsService.dropBean(uid);
        if (i <= 0)
            return R.fail("删除失败");

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE);
        return R.ok();
    }


    @ApiOperation(value = "更新启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "是否禁用 1.启用 0.禁用") @RequestParam(value = "enabled") Integer enabled
    ) {
        StoreProjects data = storeProjectsService.getByUid(uid);
        if (null == data) return R.fail("获取失败");
        if (!data.getSource().equals(1)) return R.fail("非总部信息不能操作");

        boolean l = storeProjectsService.updateEnabled(uid, enabled, headStaffUid, headStaffName);
        if (!l)
            return R.fail("更新服务状态失败");

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE);

        return R.ok();
    }


    @ApiOperation(value = "上移/下移")
    @PostMapping(value = "/upOrDown", produces = "application/json; charset=UTF-8")
    public R<Object> upOrDown(
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "类型 1.上移 2.下移") @RequestParam(value = "type") Integer type
    ) {
        StoreProjects data = storeProjectsService.getByUid(uid);
        if (null == data) return R.fail("获取失败");
        if (!data.getSource().equals(1)) return R.fail("非总部信息不能操作");

        if (type.equals(1)) {
            // 上移
            StoreProjects preData = storeProjectsService.getLtShowOrder(data.getOrderNum());
            if (preData == null) return R.fail("已在最前");
            // 和前一条记录的序号互换
            Integer prevOrderNum = preData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            storeProjectsService.updateOrderNum(preData.getUid(), curOrderNum, headStaffUid, headStaffName);
            storeProjectsService.updateOrderNum(uid, prevOrderNum, headStaffUid, headStaffName);
        } else if (type.equals(2)) {
            // 下移
            StoreProjects backData = storeProjectsService.getGtShowOrder(data.getOrderNum());
            if (backData == null) return R.fail("已在最后");
            // 和后一条记录的序号互换
            Integer backOrderNum = backData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            storeProjectsService.updateOrderNum(backData.getUid(), curOrderNum, headStaffUid, headStaffName);
            storeProjectsService.updateOrderNum(uid, backOrderNum, headStaffUid, headStaffName);
        } else {
            return R.fail("类型错误");
        }

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE);

        return R.ok();
    }


    @ApiOperation(value = "获取总部可用的收费服务列表")
    @PostMapping(value = "/getList", produces = "application/json; charset=UTF-8")
    public R<Object> getList(
            @ApiParam(value = "员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "服务名称") @RequestParam(value = "keyword", required = false) String keyword
    ) {
        List<StoreProjects> list = storeProjectsService.getList(keyword);
        return R.ok(list);
    }


    @ApiOperation(value = "获取用于轻量产品加盟的学科集合")
    @PostMapping(value = "/getOperationProjectList", produces = "application/json; charset=UTF-8")
    public R<Object> getOperationProjectList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName
    ) {
        List<StoreProjects> list = storeProjectsService.enabledList();

        return R.ok(list);
    }

    /**
     * 判断服务是否被使用
     */
    private String useProject(String projectUid) {
        boolean b = cmservicesService.haveProjectUid(projectUid);
        if (b)
            return "会员订单服务已使用，不能操作";

        // 先判断
        b = somsFeignService.haveProjectUid(projectUid);
        if (b)
            return "社团已使用，不能操作";

        b = scheduleLessonService.haveProjectUid(projectUid);
        if (b)
            return "活动已使用，不能操作";

        // 删除前先判断有没有产品记录
        b = productLogsService.haveProjectUid(projectUid);
        if (b)
            return "产品包已使用，不能操作";

        return "";
    }

}
